﻿using System;
using System.ComponentModel;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;

namespace QuickTest.AddIn
{
    [RunInstaller(true)]
    public class QuickTestInstaller : Installer
    {
        private readonly string _addinPath = Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), @"Application Data\Microsoft\MSEnvShared\Addins\QuickTest.AddIn");

        private string GetAddinXml()
        {
            XDocument linqXmlDocument = null;
            string installationPath = base.Context.Parameters["AssemblyPath"];
            string addinResourceFile = Assembly.GetExecutingAssembly().GetName().Name + ".QuickTest.AddIn";

            using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(addinResourceFile))
            {
                linqXmlDocument = XDocument.Load(XmlReader.Create(resourceStream));
            }
            var query = from assemblyNode in linqXmlDocument.Descendants()
                        where assemblyNode.Name.LocalName.ToLower().Equals("assembly")
                        select assemblyNode;

            foreach (var assemblyNode in query)
            {
                assemblyNode.SetValue(installationPath);
            }
            return linqXmlDocument.ToString();
        }

        private void WriteAddInFile(string addinXml)
        {
            var fileInfo = new FileInfo(_addinPath);
            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }
            File.WriteAllText(_addinPath, addinXml);
        }

        private void DeleteAddInFile()
        {
            if (File.Exists(_addinPath))
            {
                File.Delete(_addinPath);
            }
        }

        public override void Install(System.Collections.IDictionary stateSaver)
        {
            string addinXml = this.GetAddinXml();

            this.WriteAddInFile(addinXml);

            base.Install(stateSaver);
        }

        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            this.DeleteAddInFile();

            base.Uninstall(savedState);
        }

        public override void Rollback(System.Collections.IDictionary savedState)
        {
            base.Rollback(savedState);
        }
    }
}
